<template>
  <div id="app">
    <!-- 全局用户信息状态 -->
    <div v-if="user" class="global-user-info">
      <img 
        :src="user.avatar || 'https://via.placeholder.com/150'" 
        alt="用户头像" 
        class="global-avatar"
        @error="handleAvatarError"
      >
      <NotificationBell />
    </div>
    
    <router-view/>
  </div>
</template>

<script>
import NotificationBell from '@/components/common/NotificationBell.vue';
import apiClient from '@/utils/api'; // 导入API客户端
import { onMounted, ref } from 'vue';

export default {
  name: 'App',
  components: {
    NotificationBell
  },
  setup() {
    const user = ref(null);
    const isLoading = ref(true);
    
    // 获取当前用户信息
    const fetchCurrentUser = async () => {
      try {
        // 直接调用/user/me接口获取当前用户信息
        const response = await apiClient.get('/user/me');
        
        if (response && response.code === 200) {
          user.value = response.data;
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
        // 处理未登录情况，跳转到登录页
        if (error.message.includes('身份验证失败')) {
          window.location.href = '/login';
        }
      } finally {
        isLoading.value = false;
      }
    };
    
    // 页面加载时获取用户信息
    onMounted(() => {
      fetchCurrentUser();
    });
    
    // 头像加载错误处理
    const handleAvatarError = (event) => {
      event.target.src = 'https://via.placeholder.com/150';
    };
    
    return {
      user,
      isLoading,
      handleAvatarError
    };
  }
};
</script>

<style scoped>
.global-user-info {
  display: flex;
  align-items: center;
  gap: 16px;
  position: fixed;
  top: 16px;
  right: 16px;
  z-index: 1000;
}

.global-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>